package com.share.config.filter.log;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class LogReadResponeWrapper extends HttpServletResponseWrapper {
    private final int SIZE = 1024;
    private ByteArrayOutputStream outputStream = new ByteArrayOutputStream(SIZE);
    private PrintWriter printWriter = new PrintWriter(outputStream);


    public LogReadResponeWrapper(HttpServletResponse request) {
        super(request);
    }

    @Override
    public void flushBuffer() throws IOException {
        printWriter.flush();
        printWriter.close();

        outputStream.flush();
        outputStream.close();
    }

    //提供一个提取的接口
    public byte[] getBody() {
        return outputStream.toByteArray();
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return printWriter;
    }

    //创建一个 输出流
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener listener) {

            }

            @Override
            public void write(int b) throws IOException {
                outputStream.write(b);
            }
        };
    }
}
